import type { Request, Response } from 'express';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

// 当前用户的权限，如果为空代表没登录
let currentUser: API.UserWithRoles | null = null;

const getCurrentUser = () => {
  return currentUser;
};

// 模拟权限数据
const mockPermissions: API.Permission[] = [
  // 菜单权限
  {
    id: '1',
    name: '仪表盘',
    code: 'dashboard:view',
    type: 'menu',
    resource: '/dashboard',
    action: 'view',
    description: '查看仪表盘页面',
    sort: 1,
    status: 'active',
  },
  {
    id: '2',
    name: '用户管理',
    code: 'user:view',
    type: 'menu',
    resource: '/users',
    action: 'view',
    description: '查看用户管理页面',
    sort: 2,
    status: 'active',
  },
  {
    id: '3',
    name: '角色管理',
    code: 'role:view',
    type: 'menu',
    resource: '/roles',
    action: 'view',
    description: '查看角色管理页面',
    sort: 3,
    status: 'active',
  },
  {
    id: '4',
    name: '权限管理',
    code: 'permission:view',
    type: 'menu',
    resource: '/permissions',
    action: 'view',
    description: '查看权限管理页面',
    sort: 4,
    status: 'active',
  },
  {
    id: '5',
    name: '系统设置',
    code: 'setting:view',
    type: 'menu',
    resource: '/settings',
    action: 'view',
    description: '查看系统设置页面',
    sort: 5,
    status: 'active',
  },

  // 按钮权限
  {
    id: '6',
    name: '创建用户',
    code: 'user:create',
    type: 'button',
    resource: 'user',
    action: 'create',
    description: '创建新用户',
    sort: 6,
    status: 'active',
  },
  {
    id: '7',
    name: '编辑用户',
    code: 'user:edit',
    type: 'button',
    resource: 'user',
    action: 'edit',
    description: '编辑用户信息',
    sort: 7,
    status: 'active',
  },
  {
    id: '8',
    name: '删除用户',
    code: 'user:delete',
    type: 'button',
    resource: 'user',
    action: 'delete',
    description: '删除用户',
    sort: 8,
    status: 'active',
  },
  {
    id: '9',
    name: '分配用户角色',
    code: 'user:assign_role',
    type: 'button',
    resource: 'user',
    action: 'assign_role',
    description: '为用户分配角色',
    sort: 9,
    status: 'active',
  },

  {
    id: '10',
    name: '创建角色',
    code: 'role:create',
    type: 'button',
    resource: 'role',
    action: 'create',
    description: '创建新角色',
    sort: 10,
    status: 'active',
  },
  {
    id: '11',
    name: '编辑角色',
    code: 'role:edit',
    type: 'button',
    resource: 'role',
    action: 'edit',
    description: '编辑角色信息',
    sort: 11,
    status: 'active',
  },
  {
    id: '12',
    name: '删除角色',
    code: 'role:delete',
    type: 'button',
    resource: 'role',
    action: 'delete',
    description: '删除角色',
    sort: 12,
    status: 'active',
  },
  {
    id: '13',
    name: '配置角色权限',
    code: 'role:configure_permission',
    type: 'button',
    resource: 'role',
    action: 'configure_permission',
    description: '为角色配置权限',
    sort: 13,
    status: 'active',
  },

  {
    id: '14',
    name: '创建权限',
    code: 'permission:create',
    type: 'button',
    resource: 'permission',
    action: 'create',
    description: '创建新权限',
    sort: 14,
    status: 'active',
  },
  {
    id: '15',
    name: '编辑权限',
    code: 'permission:edit',
    type: 'button',
    resource: 'permission',
    action: 'edit',
    description: '编辑权限信息',
    sort: 15,
    status: 'active',
  },
  {
    id: '16',
    name: '删除权限',
    code: 'permission:delete',
    type: 'button',
    resource: 'permission',
    action: 'delete',
    description: '删除权限',
    sort: 16,
    status: 'active',
  },

  {
    id: '17',
    name: '编辑系统设置',
    code: 'setting:edit',
    type: 'button',
    resource: 'setting',
    action: 'edit',
    description: '编辑系统设置',
    sort: 17,
    status: 'active',
  },

  // 系统权限
  {
    id: '18',
    name: '系统管理',
    code: 'system:manage',
    type: 'api',
    resource: 'system',
    action: 'manage',
    description: '系统管理权限',
    sort: 18,
    status: 'active',
  },

  // 数据权限
  {
    id: '19',
    name: '导出数据',
    code: 'data:export',
    type: 'button',
    resource: 'data',
    action: 'export',
    description: '导出数据',
    sort: 19,
    status: 'active',
  },
  {
    id: '20',
    name: '导入数据',
    code: 'data:import',
    type: 'button',
    resource: 'data',
    action: 'import',
    description: '导入数据',
    sort: 20,
    status: 'active',
  },
];

// 模拟角色数据
const mockRoles: API.Role[] = [
  {
    id: 'role-1',
    name: '超级管理员',
    code: 'admin',
    description: '拥有系统所有权限',
    status: 'active',
    permissions: mockPermissions,
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: '2024-01-01T00:00:00Z',
  },
  {
    id: 'role-2',
    name: '系统管理员',
    code: 'system_admin',
    description: '负责系统配置和用户管理',
    status: 'active',
    permissions: mockPermissions.filter(p => 
      p.code && (!p.code.includes('permission:') || ['permission:view', 'permission:edit'].includes(p.code))
    ),
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: '2024-01-01T00:00:00Z',
  },
  {
    id: 'role-3',
    name: '用户管理员',
    code: 'user_admin',
    description: '负责用户和角色管理',
    status: 'active',
    permissions: mockPermissions.filter(p => 
      p.code && (
        p.code.includes('dashboard:view') ||
        p.code.includes('user:') ||
        p.code.includes('role:view') ||
        p.code.includes('role:create') ||
        p.code.includes('role:edit') ||
        p.code.includes('role:configure_permission')
      )
    ),
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: '2024-01-01T00:00:00Z',
  },
  {
    id: 'role-4',
    name: '普通用户',
    code: 'user',
    description: '基础查看权限',
    status: 'active',
    permissions: mockPermissions.filter(p => 
      p.code && (
        p.code === 'dashboard:view' ||
        p.code.includes('setting:view')
      )
    ),
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: '2024-01-01T00:00:00Z',
  },
  {
    id: 'role-5',
    name: '访客',
    code: 'guest',
    description: '只读权限',
    status: 'active',
    permissions: mockPermissions.filter(p => 
      p.code && (
        p.code === 'dashboard:view' ||
        p.code.includes('setting:view')
      )
    ),
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: '2024-01-01T00:00:00Z',
  },
];

// 模拟用户角色关联
const mockUserRoles: API.UserRole[] = [
  { id: 'ur-1', userId: '00000001', roleId: 'role-1' },
  { id: 'ur-2', userId: '00000002', roleId: 'role-4' },
];

// 模拟用户数据
const mockUsers: API.UserWithRoles[] = [
  {
    userid: '00000001',
    name: '管理员',
    avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    email: 'admin@example.com',
    signature: '海纳百川，有容乃大',
    title: '系统管理员',
    group: '技术部',
    access: 'admin',
    roles: [mockRoles[0]], // 超级管理员
    permissions: mockRoles[0].permissions || [],
  },
  {
    userid: '00000002',
    name: '普通用户',
    avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    email: 'user@example.com',
    signature: '好好学习，天天向上',
    title: '普通员工',
    group: '业务部',
    access: 'user',
    roles: [mockRoles[3]], // 普通用户
    permissions: mockRoles[3].permissions || [],
  },
];

export default {
  // 登录接口
  'POST /api/login/account': async (req: Request, res: Response) => {
    const { password, username, type } = req.body;
    console.log('收到登录请求:', { username, password, type });
    
    await waitTime(500);
    
    if (password === 'ant.design' && username === 'admin') {
      currentUser = {
        userid: '00000001',
        name: '管理员',
        avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
        email: 'admin@example.com',
        signature: '海纳百川，有容乃大',
        title: '系统管理员',
        group: '技术部',
        access: 'admin',
        roles: [mockRoles[0]], // 超级管理员角色
        permissions: mockPermissions, // 拥有所有权限
      };
      res.send({
        status: 'ok',
        type,
        currentAuthority: 'admin',
      });
      return;
    }
    
    if (password === 'ant.design' && username === 'user') {
      currentUser = {
        userid: '00000002',
        name: '普通用户',
        avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
        email: 'user@example.com',
        signature: '好好学习，天天向上',
        title: '普通员工',
        group: '业务部',
        access: 'user',
        roles: [mockRoles[3]], // 普通用户角色
        permissions: mockRoles[3].permissions || [], // 只有基础权限
      };
      res.send({
        status: 'ok',
        type,
        currentAuthority: 'user',
      });
      return;
    }

    res.send({
      status: 'error',
      type,
      currentAuthority: 'guest',
    });
  },

  // 退出登录
  'POST /api/login/outLogin': (_req: Request, res: Response) => {
    currentUser = null;
    res.send({ data: {}, success: true });
  },

  // 获取当前用户信息
  'GET /api/currentUser': (_req: Request, res: Response) => {
    const user = getCurrentUser();
    if (!user) {
      res.status(401).send({
        data: {
          isLogin: false,
        },
        errorCode: '401',
        errorMessage: '请先登录！',
        success: true,
      });
      return;
    }
    
    res.send({
      success: true,
      data: user,
    });
  },

  // 权限相关接口
  'GET /api/permissions': async (_req: Request, res: Response) => {
    await waitTime(300);
    res.send({
      success: true,
      data: mockPermissions,
      total: mockPermissions.length,
    });
  },

  'GET /api/permissions/tree': async (_req: Request, res: Response) => {
    await waitTime(200);
    res.send({
      success: true,
      data: mockPermissions,
    });
  },

  'POST /api/permissions': async (req: Request, res: Response) => {
    await waitTime(400);
    const newPermission: API.Permission = {
      id: `perm-${Date.now()}`,
      ...req.body,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    mockPermissions.push(newPermission);
    res.send({
      success: true,
      data: newPermission,
    });
  },

  'PUT /api/permissions/:id': async (req: Request, res: Response) => {
    await waitTime(300);
    const { id } = req.params;
    const index = mockPermissions.findIndex(p => p.id === id);
    if (index !== -1) {
      mockPermissions[index] = {
        ...mockPermissions[index],
        ...req.body,
        updatedAt: new Date().toISOString(),
      };
    }
    res.send({
      success: true,
      data: mockPermissions[index],
    });
  },

  'DELETE /api/permissions/:id': async (req: Request, res: Response) => {
    await waitTime(200);
    const { id } = req.params;
    const index = mockPermissions.findIndex(p => p.id === id);
    if (index !== -1) {
      mockPermissions.splice(index, 1);
    }
    res.send({
      success: true,
      data: {},
    });
  },

  // 角色相关接口
  'GET /api/roles': async (_req: Request, res: Response) => {
    await waitTime(300);
    res.send({
      success: true,
      data: mockRoles,
      total: mockRoles.length,
    });
  },

  'POST /api/roles': async (req: Request, res: Response) => {
    await waitTime(400);
    const newRole: API.Role = {
      id: `role-${Date.now()}`,
      ...req.body,
      permissions: [],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    mockRoles.push(newRole);
    res.send({
      success: true,
      data: newRole,
    });
  },

  'PUT /api/roles/:id': async (req: Request, res: Response) => {
    await waitTime(300);
    const { id } = req.params as any;
    const index = mockRoles.findIndex(r => r.id === id);
    if (index !== -1) {
      const updatedRole = {
        ...mockRoles[index],
        ...req.body,
        updatedAt: new Date().toISOString(),
      };
      
      // 如果有权限ID，更新权限
      if (req.body.permissionIds) {
        updatedRole.permissions = mockPermissions.filter(p => 
          p.id && req.body.permissionIds.includes(p.id)
        );
      }
      
      mockRoles[index] = updatedRole;
      res.send({
        success: true,
        data: updatedRole,
      });
    }
  },

  'DELETE /api/roles/:id': async (req: Request, res: Response) => {
    await waitTime(200);
    const { id } = req.params;
    const index = mockRoles.findIndex(r => r.id === id);
    if (index !== -1) {
      mockRoles.splice(index, 1);
    }
    res.send({
      success: true,
      data: {},
    });
  },

  'GET /api/roles/:id': async (req: Request, res: Response) => {
    await waitTime(200);
    const { id } = req.params;
    const role = mockRoles.find(r => r.id === id);
    res.send({
      success: true,
      data: role,
    });
  },

  // 用户相关接口
  'GET /api/users': async (_req: Request, res: Response) => {
    await waitTime(300);
    res.send({
      success: true,
      data: mockUsers,
      total: mockUsers.length,
    });
  },

  'POST /api/users': async (req: Request, res: Response) => {
    await waitTime(400);
    const newUser: API.UserWithRoles = {
      userid: `user-${Date.now()}`,
      ...req.body,
      avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
      roles: [],
      permissions: [],
    };
    mockUsers.push(newUser);
    res.send({
      success: true,
      data: newUser,
    });
  },

  'PUT /api/users/:id': async (req: Request, res: Response) => {
    await waitTime(300);
    const { id } = req.params as any;
    const index = mockUsers.findIndex(u => u.userid === id);
    if (index !== -1) {
      mockUsers[index] = {
        ...mockUsers[index],
        ...req.body,
      };
    }
    res.send({
      success: true,
      data: mockUsers[index],
    });
  },

  'DELETE /api/users/:id': async (req: Request, res: Response) => {
    await waitTime(200);
    const { id } = req.params;
    const index = mockUsers.findIndex(u => u.userid === id);
    if (index !== -1) {
      mockUsers.splice(index, 1);
    }
    res.send({
      success: true,
      data: {},
    });
  },

  'POST /api/users/:userId/roles': async (req: Request, res: Response) => {
    await waitTime(300);
    const { userId } = req.params as any;
    const { roleIds } = req.body;
    
    const userIndex = mockUsers.findIndex(u => u.userid === userId);
    if (userIndex !== -1) {
      const assignedRoles = mockRoles.filter(r => roleIds.includes(r.id));
      mockUsers[userIndex].roles = assignedRoles;
      mockUsers[userIndex].permissions = assignedRoles.flatMap(r => r.permissions || []);
    }
    
    res.send({
      success: true,
      data: {},
    });
  },

  'GET /api/users/:id/permissions': async (req: Request, res: Response) => {
    await waitTime(200);
    const { id } = req.params;
    const user = mockUsers.find(u => u.userid === id);
    res.send({
      success: true,
      data: user?.permissions || [],
    });
  },
};
